import urllib
import requests
from concurrent.futures import ThreadPoolExecutor
from queue import Queue
import threading
import datetime
import sys


class Music:

    def __init__(self, name, type_str, number):
        self.number = number
        self.event = threading.Event()
        self.executor = ThreadPoolExecutor(6)
        self.name = name
        self.type_str = type_str
        self.url = "https://music.liuzhijin.cn"
        self.q1 = Queue()
        self.q2 = Queue()
        self.session = requests.session()
        self.headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36",
        "Origin": "https://music.liuzhijin.cn",
        "Referer": f"https://music.liuzhijin.cn/?name={urllib.parse.quote(name)}&type={type_str}",
        "Content-length": "60",
        "x-requested-with": "XMLHttpRequest",
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Cookie": "Hm_lvt_50027a9c88cdde04a70f5272a88a10fa=1588730383; Hm_lpvt_50027a9c88cdde04a70f5272a88a10fa=1588753180"
    }

        self.collection_page()

    def post(self):
        while not self.event.is_set():
            page = self.q1.get()
            items = {"input": self.name,
                     "filter": "name",
                     "type": self.type_str,
                     "page": page}
            res = self.session.post(url=self.url, headers=self.headers, data=items)
            self.q2.put(res)  # 慢
        # res_post

    def get_data(self):
        res_post = self.q2.get()
        return map(lambda x: (x.get("url", ""), x.get('title'), x.get("songid")), res_post.json()['data'])

    def collection_page(self):
        for page in range(1, self.number+1):
            self.q1.put(page)

    def download(self):
        start = datetime.datetime.now()
        tasks = [self.post, self.post, self._download, self._download, self._download, self._download]
        for task in tasks:
            self.executor.submit(task)
        while not input():
            end = datetime.datetime.now()
            print((end-start).total_seconds())
        print("end")
        self.executor.shutdown()
        sys.exit(0)


    def _download(self):
        i = 0
        while not self.event.is_set():
            for url, title, sid in self.get_data():
                if url:
                    i += 1
                    res = self.session.get(url, stream=True)
                    with open(f"./ms/{title}{sid}.{url.rpartition('.')[-1]}", 'wb')as f:
                        for chunk in res.iter_content(1024*200):
                            f.write(chunk)
                    print(f"正在下载{i}@@@{title}{sid}")